package sb.simple.wrapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sb.simple.wrapper.common.CommonResult;
import sb.simple.wrapper.common.CustomException;
import sb.simple.wrapper.common.OtherErrorEnum;
import sb.simple.wrapper.pojo.User;
import sb.simple.wrapper.pojo.User4ResultMap;
import sb.simple.wrapper.service.WrapperService;

import java.util.List;

@Controller
@RequestMapping("wrapper")
@CrossOrigin//解决跨域问题
public class WrapperController {

    @Autowired
    WrapperService wrapperService;

    @PostMapping("insertUser")
    public void insertUser(User4ResultMap user) {
        wrapperService.insert(user);
    }

    @ResponseBody
    @GetMapping("getUsers")
    public CommonResult getUsers() {
        List<User> users = wrapperService.getUsers();
        for (User user : users) {
            System.out.println(user.toString());
        }
        return CommonResult.defineSuccess(users);
    }

    @ResponseBody
    @GetMapping("getUsers4ResultMap")
    public CommonResult getUsers4ResultMap() {
        List<User4ResultMap> users = wrapperService.getUsers4ResultMap();
        for (User4ResultMap user : users) {
            System.out.println(user.toString());
        }
        return CommonResult.defineSuccess(users);
    }

    @ResponseBody
    @GetMapping("hello")
    public String hello() {
        System.out.println("hello");
        return "hello";
    }

    //客户端传raw+json
    //python:headers = {'content-type': "application/json"}
    //requests.post(url=,headers=,data=json.dumps(dict))
    @PostMapping("testBody")
    public String testBody(@Validated @RequestBody User user) {
        System.out.println("testBody() user:" + user.toString());
        return user.toString();
    }

    @GetMapping("error")
    @ResponseBody
    public String error(@RequestParam("index") String index) {
        switch (index) {
            case "0":
                return new CommonResult(true, 200, "success", "temp").toString();
            default:
                throw new CustomException(OtherErrorEnum.INTERNAL_SERVER_ERROR.getErrorCode(), OtherErrorEnum.INTERNAL_SERVER_ERROR.getErrorMsg());
        }
    }

}
